const path = require('path');
const Koa = require('koa');
const xml2js = require("xml2js");
const koaBody = require("koa-body");
const static = require('koa-static');
const views = require('koa-views');
const Router = require('koa-router');
const { validateWechatHost } = require("./utils/validateWechatHost")
const { createResData } = require('./utils/createRespondData')
const { createUser } = require("./controller/userOperator/index")
const { sendCouponMsg } = require("./utils/sendMsg");

const app = new Koa();


app.use(koaBody({ json: true }))
app.use(static(path.join(__dirname, '/static')))
app.use(views('./view', { map: { "html": 'ejs' } }))
const router = new Router();
app.use(router.routes())

/** 默认回复信息，一个get一个post */
router.post('/valid', async (ctx, next) => {
    console.log('打印***ctx.request.body', ctx.request.body)

    const xmlData = ctx.request.body;
    // xml 对象
    const { xml } = await xml2js.parseStringPromise(xmlData);
    let xmlJson = {}
    for (let item in xml) {
        xmlJson[item] = xml[item][0]
    }

    if (xmlJson.MsgType === 'text') {
        // await createUser(xmlJson.FromUserName, xmlJson.ToUserName)
        xmlJson = await sendCouponMsg(xmlJson)
    }

    const resMsg = createResData(xmlJson)
    ctx.body = resMsg
})



/** 验证接受开发者服务器的资源，只有写好接口，才能添加地址和token */
router.get('/valid', async (ctx, next) => {
    const { echostr, isWechatHost } = validateWechatHost(ctx)
    console.log('打印***echostr', echostr)
    console.log('打印***isWechatHost', isWechatHost)
    if (isWechatHost) {
        ctx.body = echostr
    } else {
        ctx.body = 'none'
    }
})

app.listen('8888')
console.log('serve is on at http://localhost:8888')